package start

import (
	"fmt"
	"gitee.com/maomaomaoge/opmq"
	"github.com/spf13/cobra"
	"net"
)

var D *Data

type Data struct {
	YamlPath string
}

var Start = &cobra.Command{
	Use:   "start",
	Short: "start short",
	Example: `
	# 如果不添加参数，默认为1883端口
	mqctl start -p 1883 -y etc/app.yaml
`,
	Run: func(cmd *cobra.Command, args []string) {
		work()
	},
}

func init() {
	D = &Data{}
	Start.Flags().StringVarP(&D.YamlPath, "yaml_path", "y", "", "配置文件路径")
}

func work() {
	if D.YamlPath == "" {
		opmq.DEBUG.Println("配置文件路径不能为空")
		return
	}

	viper, err := opmq.Viper(D.YamlPath)
	if err != nil {
		opmq.PANIC.Println(err)
	}

	user := viper.GetString("UserName")
	pwd := viper.GetString("pwd")
	Dashboard := viper.GetString("Dashboard")
	Api := viper.GetString("Api")
	MqttPort := viper.GetString("MqttPort")

	// 集群相关配置
	IsOpenCluster := viper.GetBool("IsOpenCluster")
	IsMaster := viper.GetString("IsMaster")
	ClusterId := viper.GetString("ClusterId")
	NodeIp := viper.GetString("NodeIp")
	SlaveToMaster := viper.GetString("SlaveToMaster")
	RpcPort := viper.GetString("RpcPort")
	MasterRpcPort := viper.GetString("MasterRpcPort")

	opts := make([]opmq.Options, 0)
	opts = append(opts, opmq.WithAuth(user,pwd), opmq.WithHTTP(Dashboard, Api), opmq.WithMqttPort(MqttPort), opmq.WithClusterRemoteMasterIp(SlaveToMaster),
		opmq.WithClusterRpcPort(RpcPort), opmq.WithClusterMasterRpcPort(MasterRpcPort))

	fmt.Println("启动的端口为: ", MqttPort)
	if IsOpenCluster {
		opmq.DEBUG.Println("开启集群模式,本节点名称: ", ClusterId, " 本节主节点: ", IsMaster, " 对外ip: ", NodeIp)
		opts = append(opts, opmq.WithClusterId(ClusterId), opmq.WithIsMaster(IsMaster), opmq.WithClusterIp(NodeIp))
		l, err := net.Listen("tcp", ":"+ MqttPort)
		if err != nil {
			return
		}
		opmq.Broker = opmq.NewServer(l,  opts...)
		opmq.Broker.Serve()
	} else {
		l, err := net.Listen("tcp", ":"+ MqttPort)
		if err != nil {
			return
		}
		opmq.Broker = opmq.NewServer(l, opts...)
		opmq.Broker.Serve()
	}
}
